package tmall.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import tmall.common.dto.ResponseResult;
import tmall.common.util.ApiRet;

/**
 * @description: 全局异常处理
 * @author zhangservlet
 * @date 2020/12/18
 */
@ControllerAdvice
public class ExceptionsHandler {
    protected final Logger logger = LogManager.getLogger(ExceptionsHandler.class);

    @ResponseBody
    @ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类，会自动映射
    public ResponseResult customGenericExceptionHandler(CustomGenericException e){ //还可以声明接收其他任意参数
        logger.error(e);
        return ApiRet.failed(e.getErrMsg(), e.getErrCode());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)//可以直接写@EceptionHandler，IOException继承于Exception
    public ResponseResult allExceptionHandler(Exception e){
        e.printStackTrace();
        logger.error(e);
        return ApiRet.failed(e.getMessage(), ReturnCode.FAILED);
    }


    @ResponseBody
    @ExceptionHandler(NotLoginException.class)
    public ResponseResult loginExceptionHandler(Exception e){
        logger.error(e);
        return ApiRet.failed("用户未登录", ReturnCode.FAILED);
    }

    @ResponseBody
    @ExceptionHandler(NotRoleException.class)
    public ResponseResult notRoleException(Exception e){
        logger.error(e);
        return ApiRet.failed("用户没有对应角色权限", ReturnCode.FAILED);
    }
}
